package com.sx.springbootshiro.common.shiro;

import com.sx.springbootshiro.model.LoginPermissionVB;
import com.sx.springbootshiro.model.LoginRolesVB;
import com.sx.springbootshiro.model.LoginUserVB;
import com.sx.springbootshiro.service.LoginUserService;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class CustomRealm extends AuthorizingRealm {
    private Logger logger = LogManager.getLogger(CustomRealm.class);

    @Autowired
    private LoginUserService loginUserService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取登录用户名
        String user_nickname = (String) principalCollection.getPrimaryPrincipal();
        //数据库查询信息
        LoginUserVB loginUser = loginUserService.selectLoginUserVBByUserNickname(user_nickname);
        //添加角色和权限
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        for (LoginRolesVB role : loginUser.getLoginRolesVBS()) {
            //添加角色
            simpleAuthorizationInfo.addRole(role.getRole_name());
            //添加权限
            for (LoginPermissionVB permissions : role.getLoginPermissionVBS()) {
                simpleAuthorizationInfo.addStringPermission(permissions.getPermission_name());
            }
        }
        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //加这一步的目的是在Post请求的时候会先进认证，然后在到请求
        if (authenticationToken.getPrincipal() == null) {
            return null;
        }
        //获取用户信息
        String user_nickname = authenticationToken.getPrincipal().toString();
        LoginUserVB loginUserVB = loginUserService.selectLoginUserVBByUserNickname(user_nickname);
        if (loginUserVB == null) {
            //这里返回后会报出对应异常
            return null;
        } else {
            //这里验证authenticationToken和simpleAuthenticationInfo的信息
            SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(user_nickname, loginUserVB.getUser_password(), getName());
            return simpleAuthenticationInfo;
        }
    }
}
